package com.xstar.game.gameoflife;

import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class Main {
    // 迭代延迟 ms
    public static final int delay = 1000 / 10;

    // 细胞数量
    public static final int WIDTH = 128;
    public static final int HEIGHT = 128;

    // 细胞群落
    public static final CellGroup cellGroup = new CellGroup(WIDTH, HEIGHT);

    // 绘制层
    public static GameView view;

    private static void createAndShowGUI() {
        // 创建及设置窗口
        int w = 785;
        int h = 825;
        JFrame frame = new JFrame("Game of Life");
        frame.setBounds(0, 0, w, h);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null);
        frame.setResizable(false);

        // 绘图
        view = new GameView(5);
        int view_w = view.width * cellGroup.width + cellGroup.width;
        int view_h = view.width * cellGroup.height + cellGroup.height;
        view.setBounds(0, 15, view_w, view_h);
        frame.getContentPane().add(view);

        JLabel size = new JLabel("点我随机填充 " + view_w + "x" + view_h + " " + cellGroup.width + " " + cellGroup.height);
        size.setVerticalAlignment(SwingConstants.TOP);
        size.setBounds(0, 0, view_w, 15);
        frame.getContentPane().add(size);
        size.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent mouseEvent) {
                for (int i = 0; i < HEIGHT; i++) {
                    for (int j = 0; j < WIDTH; j++) {
                        cellGroup.cells[i][j] = (int) (Math.random() * 16) % 2;
                    }
                }
            }

            @Override
            public void mousePressed(MouseEvent mouseEvent) {

            }

            @Override
            public void mouseReleased(MouseEvent mouseEvent) {

            }

            @Override
            public void mouseEntered(MouseEvent mouseEvent) {

            }

            @Override
            public void mouseExited(MouseEvent mouseEvent) {

            }
        });

        // 显示窗口
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        // 游戏进程
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(delay);

                    if (view == null)
                        continue;

                    cellGroup.iteration();
                    view.repaint();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        // 显示应用 GUI
        javax.swing.SwingUtilities.invokeLater(Main::createAndShowGUI);
    }

}
